package base

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/hibiken/asynq"
	"mall/common/globalkey"
	"mall/common/mqueuex"
	"mall/common/utils/pointy"
	"mall/service/order/rpc/orderclient"
	"mall/service/product/rpc/productclient"
	"strconv"
	"strings"

	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type InitMcmsDatabaseLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewInitMcmsDatabaseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InitMcmsDatabaseLogic {
	return &InitMcmsDatabaseLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *InitMcmsDatabaseLogic) InitMcmsDatabase() (resp *types.BaseMsgResp, err error) {
	//var labels = []string{
	//	"花香调", "果香调",
	//}
	//err = l.createItem(globalkey.GorseKnowledgeBasePrefix+"1", labels)
	//if err != nil {
	//	fmt.Println("n00i")
	//	return nil, err
	//}
	var OrderSn = "O20250604164045174516001"
	order, err := l.svcCtx.OrderRpc.GetOrderBySn(l.ctx, &orderclient.GetOrderBySnReq{
		Sn:      pointy.GetPointer(OrderSn),
		WithSku: pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		return nil, fmt.Errorf("DeferedCloseOrderProcessor Failed to get order err: %+v", err)
	}

	if order.Id == nil || order.OrderType == nil || order.TradeState == nil {
		return nil, fmt.Errorf("DeferedCloseOrderProcessor Failed to get valid data of order: %+v", order)
	}

	if *order.TradeState == globalkey.OrderTradeStateNotPay {
		_, err := l.svcCtx.OrderRpc.UpdateTradeState(l.ctx, &orderclient.UpdateTradeStateReq{
			Id:         order.Id,
			TradeState: pointy.GetPointer(globalkey.OrderTradeStateAutoCancelled),
		})
		if err != nil {
			// return errors.Wrapf(ErrCloseOrderFailed, "DeferedCloseOrderProcessor close order failed err: %+v, sn: %s ", err, p.OrderSn)
			return nil, fmt.Errorf("DeferedCloseOrderProcessor close order failed: %+v", err)
		}
	}

	if len(order.Skus) > 0 && *order.OrderType != globalkey.OrderTypeVirtual && *order.TradeState == globalkey.OrderTradeStateNotPay {
		var stocks []*productclient.ProductVariationStock
		for _, v := range order.Skus {
			if v.SkuId != nil && v.Quantity != nil && *v.SkuId > 0 && *v.Quantity > 0 {
				stocks = append(stocks, &productclient.ProductVariationStock{
					Id:    *v.SkuId,
					Stock: *v.Quantity,
				})
			}
		}
		if len(stocks) > 0 {
			_, err = l.svcCtx.ProductRpc.SubtractStockRevert(l.ctx, &productclient.CheckAndSubtractStockReq{
				Data: stocks,
			})
			if err != nil {
				return nil, fmt.Errorf("DeferedCloseOrderProcessor revert stock failed: %+v : %w", err, asynq.SkipRetry)
			}
		}
	}
	fmt.Println("success 雪人起飞！")
	err = l.unFreezePointCoupon(OrderSn)
	if err != nil {
		logx.Errorw("DeferedCloseOrderProcessor unFreezePointCoupon err", logx.Field("detail", err.Error()))
		return nil, err
	}

	return
}

func (l *InitMcmsDatabaseLogic) unFreezePointCoupon(orderSn string) error {
	m := mqueuex.DeferedUnFreezePointCouponMessage{
		OrderSn: pointy.GetPointer(orderSn),
	}
	body, err := json.Marshal(m)
	if err != nil {
		logx.Errorw("DeferedCloseOrderProcessor unFreezePointCoupon json.Marshal err", logx.Field("detail", err.Error()))
		return err
	}
	return l.svcCtx.KqDeferredUnFreezePointCouponClient.Push(string(body))
}

func (l *InitMcmsDatabaseLogic) createItem(itemId string, labels []string) error {
	err := l.svcCtx.GorseClient.CreateItem(
		l.svcCtx.Config.Query.GorseUrl,
		itemId, "", "0",
		labels, strings.Split(strconv.FormatInt(int64(globalkey.AttachmentLogKbEntry), 10), ","))
	if err != nil {
		logx.Infow("")
		return err
	}
	return nil
}
